package cool.zhoujie.fragment;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;

import java.util.ArrayList;
import java.util.List;

import cool.zhoujie.MainActivity;
import cool.zhoujie.R;
import cool.zhoujie.adapter.RecentAdapter;
import cool.zhoujie.db.DBUtil;
import cool.zhoujie.db.RecentPlay;
import cool.zhoujie.service.PlayService;

/**
 * 最近播放碎片
 */
public class RecentPlayFragment extends BaseLazyLoadFragment {

    private ListView listView;

    private List<RecentPlay> recentPlayList = new ArrayList<>();

    private RecentAdapter adapter;

    private PlayService playService;

    private PlayFragment playFragment;

    private MainActivity activity;

    private List<RecentPlay> recentPlays = new ArrayList<>();

    @Override
    public View initView(LayoutInflater inflater, ViewGroup container) {
        View view = inflater.inflate(R.layout.fragment_recent_play, container, false);
        listView = view.findViewById(R.id.recent_list);

        activity = (MainActivity) getActivity();
        playFragment = (PlayFragment) activity.getSupportFragmentManager().findFragmentByTag("fragment_songPlay");

        return view;
    }

    @Override
    public void initEvent() {
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                playService = activity.playBinder.getService();
                RecentPlay recentPlay = recentPlays.get(position);
                playMusic(recentPlay);
            }
        });
    }

    private void playMusic(RecentPlay recentPlay) {
        //播放、存储最近播放数据
        playService.initMediaPlayer(recentPlay.songPath);
        playService.play();

        DBUtil.insert(recentPlay);
        //过滤
        List<RecentPlay> recentPlayList = DBUtil.queryAll();
        for (int i = 0; i < recentPlayList.size(); i++) {
            RecentPlay recentPlay1 = recentPlayList.get(i);
            if (recentPlay1.songName.equals(recentPlay.songName) && recentPlay1.artistName.equals(recentPlay.artistName)) {
                DBUtil.delete(recentPlay1);
            }
        }

        playFragment.current_state = PlayFragment.STATE_PLAY;
        playFragment.updateView(recentPlay);
    }

    @Override
    public void onLazyLoad() {
        Log.d("碎片加载状态", "每日推荐状态碎片开始加载");
        showList();
    }

    public void showList() {
        recentPlayList = DBUtil.queryAll();
        if (recentPlayList.size() > 0) {
            for (int i = recentPlayList.size() - 1; i > -1; i--) {
                recentPlays.add(recentPlayList.get(i));
            }
            adapter = new RecentAdapter(getActivity(), R.layout.list_view_item, recentPlays);
            listView.setAdapter(adapter);
        }
    }

}
